package com.taobao.mrs.zookeeper.test;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class ZooKeeperWatcher  implements Watcher{

	private final List<ZooKeeperListener> listeners =
	    new CopyOnWriteArrayList<ZooKeeperListener>();
	
	private ZooKeeper zooKeeper;
	
	public ZooKeeperWatcher(){
		try {
			this.zooKeeper=new ZooKeeper("10.232.128.65:2181", 500000,this);
		} catch (final IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public ZooKeeper getZooKeeper() {
		return zooKeeper;
	}
	public void setZooKeeper(ZooKeeper zooKeeper) {
		this.zooKeeper = zooKeeper;
	}
	
	@Override
	public void process(WatchedEvent event) {
		// TODO Auto-generated method stub

	    System.out.println("Received ZooKeeper Event, " +
	        "type=" + event.getType() + ", " +
	        "state=" + event.getState() + ", " +
	        "path=" + event.getPath());

	    switch(event.getType()) {

	      // If event type is NONE, this is a connection status change
	      case None: {
	        
	        break;
	      }

	      // Otherwise pass along to the listeners

	      case NodeCreated: {
	        for(ZooKeeperListener listener : listeners) {
	          listener.nodeCreated(event.getPath());
	        }
	        break;
	      }

	      case NodeDeleted: {
	        for(ZooKeeperListener listener : listeners) {
	          listener.nodeDeleted(event.getPath());
	        }
	        break;
	      }

	      case NodeDataChanged: {
	        for(ZooKeeperListener listener : listeners) {
	          listener.nodeDataChanged(event.getPath());
	        }
	        break;
	      }

	      case NodeChildrenChanged: {
	        for(ZooKeeperListener listener : listeners) {
	          listener.nodeChildrenChanged(event.getPath());
	        }
	        break;
	      }
	    }
	}

	 /**
	   * Register the specified listener to receive ZooKeeper events.
	   * @param listener
	   */
	  public void registerListener(ZooKeeperListener listener) {
	    listeners.add(listener);
	  }

	  /**
	   * Register the specified listener to receive ZooKeeper events and add it as
	   * the first in the list of current listeners.
	   * @param listener
	   */
	  public void registerListenerFirst(ZooKeeperListener listener) {
	    listeners.add(0, listener);
	  }
}
